﻿// ***********************************************************************
// Assembly         : TCPServerSocket
// Author           : yubao
// Created          : 07-18-2014
//
// Last Modified By : yubao
// Last Modified On : 07-29-2014
// ***********************************************************************
// <copyright file="ZLANServer.cs" company="www.cnblogs.com/dotcpp">
//     Copyright (c) www.cnblogs.com/dotcpp. All rights reserved.
// </copyright>
// <summary>TCP servver</summary>
// ***********************************************************************
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Linq;
using System.Collections;
namespace WPFExcelReport
{
    public class ZLANServer
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        const int NumOfThread = 2;
        public bool IsListening { get; private set; } 
      
        private Thread _listenthread;
        private TcpListener _listen;
        public Dictionary<string, object> ENVMAIN
        {
            get
            {
                return app.ENVMAIN(app.ServiceUri);
            }
        }
        public VICC_ZLAN VZL
        {
            get
            {
                if (!ENVMAIN.ContainsKey("VZL"))
                    return null;
                return (VICC_ZLAN)ENVMAIN["VZL"];
            }
        }
        private DataTable _TBZL;
        public DataTable TBZL
        {
            get
            {
                if (_TBZL == null)
                {
                    VZL.dwData = VZL.TBMain.NewRow();
                    VZL.dwData["MANDANT"] = app.Mandant;
                    VZL.SResult = VZL.QICC_ZLAN05(VZL.dwData);
                    _TBZL = VZL.SResult.Tables[0].Copy();
                }
                return _TBZL;
            }
        }
        DataTable _TBZLAM;
        public DataTable TBZLAM
        {
            get
            {
                if (_TBZLAM == null)
                {
                    VZL.dwData = VZL.TBMain.NewRow();
                    VZL.dwData["MANDANT"] = app.Mandant;
                    VZL.SResult = VZL.QICC_ZLAN03(VZL.dwData);
                    _TBZLAM = VZL.SResult.Tables[0].Copy();
                }
                return _TBZLAM;
            }
        }
        ZLANClient Client;
        Dictionary<string, ZLANClient> _Clients;
        public Dictionary<string, ZLANClient> Clients
        {
            get
            {
                if (_Clients == null)
                {
                    _Clients = new Dictionary<string, ZLANClient>();
                }
                return _Clients;
            }
        }
        #region 委托
        /// <summary>
        ///收到新的客户端
        /// </summary>
        public Action<ZLANClient> RecvNewClientAction;
        /// <summary>
        /// 失去连接
        /// </summary>
        public Action<ZLANClient> LostClientAction;
        /// <summary>
        /// 接收数据
        /// </summary>
        public Action<string, byte[], int> RecvDataAction;
        #endregion
        public int ServicePort = 1;
        public ZLANServer(int pointInt)
        {
            IsListening = false;
            ServicePort = pointInt; 
        }

        public void ZLStopListen()
        {
            IsListening = false;
            
            // Close all client connections
           
            _listen.Server.Close();
            _listenthread.Abort();
        }
        public void StartListen()
        {
            if (IsListening) return;
            IPAddress localIp = app.SockeSerIP;
            IsListening = true;
           
            _listen = new TcpListener(localIp, ServicePort);
            _listen.Start();
            _listenthread = new Thread(ListenThread);
            _listenthread.Start();
        }
        public void ZLResetListen()
        {
            _TBZL = null;
            _TBZLAM = null;
            foreach (KeyValuePair<string, ZLANClient> kp in Clients)
            {
                kp.Value.CloseConnection();
            }
            if (TBZL == null)
            {

            }
            if (TBZLAM == null)
            {
                app.IsOnline = true;
            }
            StartListen();
        } 

       
        private void ListenThread()
        {
            while (IsListening)
            {
                try
                {
                    Socket client = _listen.AcceptSocket();
                    Client = new ZLANClient(client);
                    if (TBZL == null)
                    {
                        if (TBZLAM == null)
                        {
                            app.IsOnline = true;
                        }
                    }
                    Client.TBZLAM = TBZLAM;
                    Client.TBZL = TBZL;
                    string ip = Client.PLCIP;
                    bool IsLogged = Client.GetDevTyp();//这里确定是否是ZLAN设备
                    if (!IsLogged)//有新设备加入
                    {
                        _TBZLAM = null;
                        _TBZL = null;
                        if (TBZL == null)
                        {
                        }
                        if (TBZLAM == null)
                        {
                        }
                    } 
                    Clients[Client.PLCIP] = Client;
                    Client.ZLAUTOREAD();
                    // PLCIP = ip;根据IP地址核对是否存在
                    //将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合  
                    Helpers.LogHelper.info("ZLANServer:"+ ip + "...Client joined......"); 
                }
                catch (Exception e)
                {
                }
            }
        }
        
       
        /// <summary>
        /// 向客户端发送消息
        /// </summary>
        /// <param name="strMsg"></param>
        string filter;
        DataRow[] rows;
        public void ZLSEND(Dictionary<string, object> pm)
        {
            try
            {
                string CHANNEL = (string)pm["CHANNEL"];
                filter = "TRIM(AMEBDEKEN) ='" + CHANNEL.Trim() + "'";
                rows = TBZL.Select(filter);
                if (rows.Length == 0)
                {
                    throw new Exception("Please check the listening status～～");
                }
                string ip = rows[0]["LOCALIP"].ToString().Trim();
                if (!Clients.ContainsKey(ip))
                {
                    throw new Exception("Please check the listening status～～");
                }

                Client = Clients[ip];
                Client.ZLSEND(pm);
            }
            catch (Exception ex)
            {
                Helpers.LogHelper.error(ex.Message);
            }
        }
        public void ZLREAD(Dictionary<string, object> pm)
        {
            try
            {


            }
            catch (Exception ex)
            {
                Helpers.LogHelper.error(ex.Message);
            }
        }
        public void ZLSTOPAM(Dictionary<string, object> pm)
        {
            lock (thisLock)
            {

                /*
                string MSETID = (string)pm["MSETID"];
                List<long> keys = new List<long>();
                foreach (KeyValuePair<long, CommandQ> kp in TimingJob)
                {
                    if (kp.Value.MSETID == MSETID)
                    {
                        keys.Add(kp.Key);
                    }
                }

                foreach (long key in keys)
                {
                    TimingJob.Remove(key);
                }
                */
            }

        }


        Object thisLock = new Object();

 
    }
}
